package com.alingrad.android.froyoengine.collisions;

import android.graphics.Matrix;
import android.graphics.RectF;

import com.alingrad.android.froyoengine.AllocationGuard;

public class CollisionMask extends AllocationGuard {
	private float mX;
	private float mY;
	private float mScaleX;
	private float mScaleY;
	private float mRotation;
	private Matrix mTransformMatrix; 
	private CollisionMaskData mData;

	public RectF mBounds;

	public CollisionMask() {
		super();
		mScaleX = 1f;
		mScaleY = 1f;
		mRotation = 0f;
		mTransformMatrix = new Matrix();
		mBounds = new RectF();
	}

	public CollisionMask update(final CollisionMaskData data, final float x, final float y) {
		return update(data, x, y, 1f, 1f, 0f);
	}
	
	public CollisionMask update(final CollisionMaskData data, final float x, final float y, final float rotation, final float scaleX, final float scaleY) {
		mX = x;
		mY = y;
		mScaleX = scaleX;
		mScaleY = scaleY;
		mRotation = rotation;
		if (data != null) {
			mData = data;
		}
		updateBoundingBox();
		return this;
	}

	private void updateBoundingBox() {
		mBounds.left = mX + mData.mLeft;
		mBounds.right = mBounds.left + mData.mWidth - 1;
		mBounds.bottom = mY + mData.mBottom;
		mBounds.top = mBounds.bottom + mData.mHeight - 1;
		if (!(mScaleX == 1f && mScaleY == 1f && mRotation == 0)) {
			mTransformMatrix.reset();
			mTransformMatrix.setScale(mScaleX, mScaleY, mX, mY);
			mTransformMatrix.postRotate(mRotation, mX, mY);
			mTransformMatrix.mapRect(mBounds);
		}
	}

	public boolean checkBoundingBoxCollision(final float x, final float y) {
		return mBounds.contains(x, y);
	}

	public boolean checkBoundingBoxCollision(final CollisionMask other) {
		return mBounds.intersect(other.mBounds);
	}

	public boolean checkCollision(final float x, final float y) {
		if (checkBoundingBoxCollision(x, y))
			return true;
		return false;
	}

	public boolean checkCollision(final CollisionMask other) {
		if (checkBoundingBoxCollision(other))
			return true;
		return false;
	}
}
